<template>
  <div class="chart"></div>
</template>

<script setup name="BarChart">
// 柱状图
import * as echarts from 'echarts'
import useResize from '@/components/Charts/hooks/useResize.js'
import { emitter } from '@/utils/EventBus.js'

const { proxy } = getCurrentInstance()
const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {
        xAxis: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        series: [120, 200, 150, 80, 70, 110, 130]
      }
    }
  }
})

let chartInstance = null

function chartInit() {
  chartInstance = echarts.init(proxy.$el, 'macarons')

  if (!props?.options?.xAxis?.length || !props?.options?.series?.length) {
    return
  }

  chartInstance.setOption({
    grid: {
      // left: 0,
      // right: 0,
      top: 20,
      bottom: 20
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: props.options.xAxis,
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: false
      }
    },
    series: [
      {
        data: props.options.series,
        type: 'bar'
      }
    ]
  }, true)
}

onMounted(() => {
  chartInit()
})
// 销毁
onBeforeUnmount(() => {
  chartInstance?.dispose()
})

watch(
  () => props.options,
  () => {
    nextTick(() => {
      chartInit()
    })
  }
)

function resize() {
  chartInstance.resize()
}

useResize(() => {
  resize()
})
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
